﻿using LD.Common;
using LD.PLC;
using LD.Quartz;
using LD.Vision;
using PubSub;
using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;

namespace LD.Host
{
    public partial class HomePage : Form
    {
        string fileUI = Path.Combine(Appbus.BasePath, "Config\\ui.xml");
        string n_userId = Guid.NewGuid().ToString();
        string n_stateEnum = Guid.NewGuid().ToString();
        object obj = new object();

        public HomePage()
        {
            InitializeComponent();
            this.Load += HomePage_Load;
            this.Shown += HomePage_Shown;

            UpdateLanguage();
        }
        private void UpdateLanguage()
        {
            this.Text = Language.GetString("Title");
            this.toolStripMenuItem1.Text = Language.GetString("System");
            this.主页toolStripMenuItem.Text = Language.GetString("homepage");
            this.配方ToolStripMenuItem.Text = Language.GetString("formula");
            this.通讯ToolStripMenuItem.Text = Language.GetString("communication");
            this.设置ToolStripMenuItem.Text = Language.GetString("set up");
            this.日志ToolStripMenuItem.Text = Language.GetString("journal");
            this.工具ToolStripMenuItem.Text = Language.GetString("tool");
            this.流程ToolStripMenuItem.Text = Language.GetString("technological process");
            this.参数ToolStripMenuItem.Text = Language.GetString("global variable");
            this.默认布局toolStripMenuItem4.Text = Language.GetString("Default Layout");
            this.保存布局ToolStripMenuItem.Text = Language.GetString("Save Layout");
            this.tsm_bc.Text = Language.GetString("Motion control");
            this.tsbitem_axisset.Text = Language.GetString("Motion control");
            this.故障报警ToolStripMenuItem.Text = Language.GetString("Fault alarm");
            this.iO操作ToolStripMenuItem.Text = Language.GetString("IO operation");
            this.toolStripMenuItem4.Text = Language.GetString("Manual operation");
            this.报表ToolStripMenuItem.Text = Language.GetString("report form");
            this.tsmitem_language.Text = Language.GetString("language");
            //this.toolStripMenuItem7.Text = Language.GetString("Chinese");
            this.toolStripMenuItem2.Text = Language.GetString("help");
            this.操作说明ToolStripMenuItem.Text = Language.GetString("Operating instructions");
            this.关于ToolStripMenuItem.Text = Language.GetString("help");
            this.toolStripStatusLabel1.Text = Language.GetString("HomePage.SystemTime");
            this.toolStripStatusLabel2.Text = Language.GetString("HomePage.User");
            this.登录ToolStripMenuItem.Text = Language.GetString("HomePage.Login");
            this.修改密码ToolStripMenuItem.Text = Language.GetString("HomePage.ChangePassword");
            this.注销ToolStripMenuItem.Text = Language.GetString("HomePage.Logout");
            this.tsmenu_ioExtend.Text = Language.GetString("IO Extend");
        }
        private void HomePage_Load(object sender, EventArgs e)
        {
            LoadUI();
        }

        private void HomePage_Shown(object sender, EventArgs e)
        {
            RegeditEvent();

            LoadMes();

            LoadBc();

            LoadVision();

            AppLoader.LoadFlow(FlowType.启动项);

            AutoRun();
        }
        private void AutoRun()
        {
            if (Cache.GetCache(CONST.SYS_SOURCE_RUN) != null)
            {
                if ((bool)Cache.GetCache(CONST.SYS_SOURCE_RUN))
                {
                    tsb_start_Click(this.tsb_start, new EventArgs());
                }
            }
        }
        private void ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string frmName = string.Empty;
            if (sender.GetType() == typeof(ToolStripMenuItem))
            {
                var tool = sender as ToolStripMenuItem;
                frmName = tool.Tag?.ToString();
            }
            else if (sender.GetType() == typeof(ToolStripButton))
            {
                var tool = sender as ToolStripButton;
                frmName = tool.Tag?.ToString();
            }
            else
            {
                return;
            }
            if (frmName == null) return;
            foreach (DockContent item in this.dockPanel1.Contents)
            {
                string _name = item.CompanyName + "." + item.Name;
                if (frmName.Equals(_name))
                {
                    item.Activate();
                    return;
                }
            }
            var frm = (DockContent)OpenFrom(frmName);
            if (frm != null)
            {
                frm.Show(this.dockPanel1, DockState.Document);
            }
        }
        private void 注销ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Appbus.User.CurrentUser = new TB_User() { Name = UserType.操作工.ToString() };
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            tslab_time.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            GC.Collect();
        }

        private void FrmHome_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult.No == MessageBox.Show("确认退出？？？", "警告", MessageBoxButtons.YesNo))
            {
                e.Cancel = true;
            }
            else
            {
                UnRegeditEvent();
                AppLoader.Closed();
                CloseDockFrm();
            }
        }

        private void 登录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmLogin frmLogin = new FrmLogin();
            frmLogin.ShowDialog();
        }

        private void 修改密码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmPwdEdit pwd = new FrmPwdEdit(Appbus.User.CurrentUser);
            pwd.ShowDialog();
        }

        private void tsb_helper_Click(object sender, EventArgs e)
        {
        }

        private void tsb_connection_Click(object sender, EventArgs e)
        {
        }

        private void tsb_user_Click(object sender, EventArgs e)
        {
            FrmLogin frmLogin = new FrmLogin();
            frmLogin.ShowDialog();
            frmLogin.Dispose();

            //if (Appbus.User.CurrentUser != null && Appbus.User.CurrentUser.Name == UserType.管理员.ToString())
            //    运动控制ToolStripMenuItem.Visible = true;
            //else
            //    运动控制ToolStripMenuItem.Visible = false;

            //this.tsbtn_user.Text = Appbus.User.CurrentUser.Name;

        }

        private void tsb_stop_Click(object sender, EventArgs e)
        {
            this.tsb_save.Enabled = true;
            Appbus.StateEnum = StateEnum.手动模式;
            Log4.Warr(Language.GetString("HomePage.Hand"));
        }

        private void tsb_start_Click(object sender, EventArgs e)
        {
            if ((bool)Cache.GetCache(CONST.BC) && !(bool)Cache.GetCache(CONST.BC_ISRESET))
            {
                Log4.Warr(Language.GetString("HomePage.ResetWarr"));
                return;
            }
            if (BCAlertHelper.GetErrorQty)
            {
                Log4.Warr(Language.GetString("HomePage.GetErrorQty"));
                return;
            }
            // 固定按钮启动
            Variable data = Cache.Var.Where(x => x.Name == "IsGS").SingleOrDefault();
            if (data != null)
            {
                data.Val = false;
                Cache.SaveCache();
            }
            //TB_IO io = BcFactory.Instance.Config.IoList.Where(p => p.Name == "检测产品" && p.IoType == (int)IoType.输入).SingleOrDefault();
            //if (data != null && Convert.ToBoolean(data.Val) && BcFactory.Instance.Control.GetIn(Convert.ToUInt16(io.No)) == (ushort)LevelType.低电平)
            //{
            //    Log4.Warr("请先取走产品再重新启动");
            //    return;
            //}
            this.tsb_start.Enabled = false;
            FlowHelper.StartAll();
            this.tsb_stop.Enabled = true;
            this.tsb_save.Enabled = false;
            Log4.Warr(Language.GetString("HomePage.Auto"));
        }

        private void tsb_output_Click(object sender, EventArgs e)
        {
            InvokeMethod("Output");
        }

        private void tsb_input_Click(object sender, EventArgs e)
        {
            InvokeMethod("Input");
        }

        private void tsb_refresh_Click(object sender, EventArgs e)
        {
            InvokeMethod("MRefresh");
        }

        private void tsb_save_Click(object sender, EventArgs e)
        {
            tsb_save.Enabled = false;
            InvokeMethod("Save");
            tsb_save.Enabled = true;
        }

        private void tsb_new_Click(object sender, EventArgs e)
        {
            tsb_new.Enabled = false;
            InvokeMethod("New");
            tsb_new.Enabled = true;
        }

        private void 保存布局ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            File.Delete(fileUI);
            dockPanel1.SaveAsXml(fileUI);
        }

        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmAbout frmAbout = new FrmAbout();
            frmAbout.ShowDialog();
        }

        private void 运动控制ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //FrmBcMain frmBcMain = new FrmBcMain();
            //frmBcMain.ShowDialog();
        }
        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
        }

        private IDockContent GetContentFromPersistString(string frmName)
        {
            return OpenFrom(frmName);
        }
        private IDockContent OpenFrom(string frmName)
        {
            IDockContent dockContent = null;
            if (!string.IsNullOrEmpty(frmName))
            {
                Type type = Type.GetType(frmName);
                if (type != null)
                {
                    dockContent = (IDockContent)Activator.CreateInstance(type);
                }
            }

            return dockContent;
        }
        private void InvokeMethod(string methodName)
        {
            DockContent dockContent = (DockContent)this.dockPanel1.ActiveContent;
            if (dockContent == null)
                return;

            Type type = dockContent.GetType();
            MethodInfo methodInfo = type.GetMethod(methodName);
            if (methodInfo == null)
                return;

            methodInfo.Invoke(dockContent, null);
        }
        private void LoadUI()
        {
            this.WindowState = FormWindowState.Maximized;
            tslab_partno.Text = Appbus.PartNo.CurrentPartNo;
            DeserializeDockContent m_deserializeDockContent = new DeserializeDockContent(GetContentFromPersistString);
            if (File.Exists(fileUI))
                dockPanel1.LoadFromXml(fileUI, m_deserializeDockContent);
#if DEBUG
            this.设置ToolStripMenuItem.Visible = true;
#endif
        }
        private void LoadMes()
        {
            if ((bool)Cache.GetCache(CONST.MES))
            {
                this.tsm_mes.Visible = true;
                if ((bool)Cache.GetCache(CONST.夏普))
                    this.夏普ToolStripMenuItem.Visible = true;
                if ((bool)Cache.GetCache(CONST.蓝思))
                    this.蓝思ToolStripMenuItem.Visible = true;
                if ((bool)Cache.GetCache(CONST.光弘))
                    this.光弘ToolStripMenuItem.Visible = true;
                if ((bool)Cache.GetCache(CONST.华勤))
                    this.华勤ToolStripMenuItem.Visible = true;
                if ((bool)Cache.GetCache(CONST.BYD))
                    this.bYDToolStripMenuItem.Visible = true;
                if ((bool)Cache.GetCache(CONST.朵唯))
                    this.朵唯ToolStripMenuItem.Visible = true;
                if ((bool)Cache.GetCache(CONST.富士康))
                    this.廊坊富士康ToolStripMenuItem.Visible = true;
                if ((bool)Cache.GetCache(CONST.衡阳富士康))
                    this.衡阳富士康ToolStripMenuItem.Visible = true;
                if ((bool)Cache.GetCache(CONST.东莞德普特))
                    this.东莞德普特ToolStripMenuItem.Visible = true;

            }
            else
                this.tsm_mes.Visible = false;

        }
        private void LoadBc()
        {
            if ((bool)Cache.GetCache(CONST.BC))
            {
                this.tsm_bc.Visible = true;
                AppLoader.LoadBc();
            }
            else
                this.tsm_bc.Visible = false;
        }
        private void LoadVision()
        {
            if ((bool)Cache.GetCache(CONST.VISION))
            {
                //CacheHelperVision.Load();
                this.tsm_vision.Visible = true;

            }
            else
                this.tsm_vision.Visible = false;
        }
        private void RegeditEvent()
        {
            Appbus.PartNo.PartNoChange += PartNo_PartNoChange;
            foreach (var item in CommunicateFactory.Instance.Com)
            {
                item.Value.StatusEvent += Communicate_StatusEvent;
            }
            foreach (var item in CommunicateFactory.Instance.TcpIp)
            {
                item.Value.StatusEvent += Communicate_StatusEvent;
            }
            if (PLCFactory.Instance != null)
                PLCFactory.Instance.StatusEvent += Communicate_StatusEvent;

            //用户变更
            Hub.Default.Subscribe<NotityHandler>(n_userId, (data) => UserChangeNotity(data));
            //工作模式变更
            Hub.Default.Subscribe<StateEnum>(n_stateEnum, (data) => StateEnumChangeNotity(data));
            //PLCFactory.Instance.Status = PLCFactory.Instance.Status;
            string cronTime = AppSettingHelper.GetConfigValue("CronTime");
            if (!string.IsNullOrEmpty(cronTime))
                // 每天删除数据
                QuartzUtil.AddJob<DeleteDBJob>("DeleteDBJob", cronTime);
        }
        private void StateEnumChangeNotity(StateEnum state)
        {

            if (state == StateEnum.手动模式)
            {
                if (!this.IsDisposed)
                {
                    this.Invoke(new Action(() =>
                    {
                        this.tsb_stop.Enabled = false;
                        this.tsb_start.Enabled = true;
                        this.tsb_save.Enabled = true;
                    }));
                }
            }
        }
        private void UserChangeNotity(NotityHandler notity)
        {
            if (notity.NtType == NotityType.用户)
            {
                var data = notity.Data as TB_User;
                if (!this.IsDisposed)
                {
                    this.Invoke(new Action(() =>
                    {
                        if (data != null && data.Name == UserType.管理员.ToString())
                        {
                            tsm_板卡配置.Visible = true;
                        }
                        else
                        {
                            tsm_板卡配置.Visible = false;
                        }

                        this.tsbtn_user.Text = data.Name;
                    }));
                }
            }
        }
        private void PartNo_PartNoChange(TB_PartNo partNo)
        {
            this.tslab_partno.Text = partNo.Name;
        }

        private void UnRegeditEvent()
        {
            Hub.Default.Unsubscribe(n_userId);
            Hub.Default.Unsubscribe(n_stateEnum);

            Appbus.PartNo.PartNoChange -= PartNo_PartNoChange;
            foreach (var item in CommunicateFactory.Instance.Com)
            {
                item.Value.StatusEvent -= Communicate_StatusEvent;
            }
            foreach (var item in CommunicateFactory.Instance.TcpIp)
            {
                item.Value.StatusEvent -= Communicate_StatusEvent;
            }
            if (PLCFactory.Instance != null)
                PLCFactory.Instance.StatusEvent -= Communicate_StatusEvent;
        }
        private void CloseDockFrm()
        {
            int count = dockPanel1.Contents.Count;
            IDockContent[] docks = new IDockContent[count];
            dockPanel1.Contents.CopyTo(docks, 0);
            foreach (var item in docks)
            {
                item.DockHandler.Close();
            }
        }
        private void Communicate_StatusEvent(string name, Status status)
        {
            lock (obj)
            {
                var tools = statusStrip1.Items.Find(name, false);
                if (tools.Count() == 0)
                {
                    ToolStripStatusLabel lab = new ToolStripStatusLabel();
                    lab.Text = name;
                    lab.Name = name;
                    lab.BackColor = Color.Green;
                    if (status == Status.失败)
                        lab.BackColor = Color.Red;
                    this.Invoke(new Action(() =>
                    {
                        statusStrip1.Items.Add(lab);
                    }));
                }
                else
                {
                    var tool = tools[0];
                    this.Invoke(new Action(() =>
                        {
                            if (status == Status.失败)
                                tool.BackColor = Color.Red;
                            else
                                tool.BackColor = Color.Green;
                        }));
                }
            }
        }

        private void 默认布局toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            string m_fileUI = Path.Combine(Appbus.BasePath, "Config\\defaultui.xml");
            DeserializeDockContent m_deserializeDockContent = new DeserializeDockContent(GetContentFromPersistString);
            if (File.Exists(m_fileUI))
            {
                CloseDockFrm();

                dockPanel1.LoadFromXml(m_fileUI, m_deserializeDockContent);
            }
        }

        private void 主界面ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmVisionMain.Instance.Show(this.dockPanel1, DockState.Document);
        }

        private void toolStripMenuItem7_Click(object sender, EventArgs e)
        {
            Language.Change(LanguageType.中文);
            UpdateLanguage();
        }

        private void toolStripMenuItem8_Click(object sender, EventArgs e)
        {
            Language.Change(LanguageType.英文);
            UpdateLanguage();
        }
    }
}
